package com.hellacutty.shake;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

public class CanvasActivity extends Activity {
    /** Called when the activity is first created. */
	private ShakeClass shake;
	private Handler handler = new Handler();
	private ImageView iv;
	private long start;
	private Runnable r = new Runnable(){
		@Override
		public void run() {
			// TODO Auto-generated method stub
			iv.invalidate();
		}

    };
    public void postToast(long time){
    	Toast.makeText(this, "Finished in " + time / 1000.0 + " seconds.", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	start = System.currentTimeMillis();
        super.onCreate(savedInstanceState);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.canvas);
        iv = (ImageView) findViewById(R.id.imageView1);
        iv.setImageDrawable(new Drawable(){
			private Bitmap android = BitmapFactory.decodeResource(getResources(),
		            R.drawable.android);
			private final int SHAKES_TO_WIN = 800;
			public void draw(Canvas canvas) {
				// TODO Auto-generated method stub
				
				Log.d("canvas height: ",canvas.getWidth()+"");
				Log.d("android height: ", android.getHeight()+"");
				
				int totalHeight = iv.getHeight()-android.getHeight();


                canvas.drawColor(Color.BLACK);
                double percentageOfScreen = ((shake.getShakeCount()+0.0)/SHAKES_TO_WIN);
                float currentHeight = (float)percentageOfScreen*totalHeight;
                canvas.drawBitmap(android, (iv.getWidth() - android.getWidth()) / 2, currentHeight, null);

                if(percentageOfScreen >= 1){
                	long totalLength = System.currentTimeMillis()-start;
                	Log.d("SHAKETAG", ""+totalLength);
                	postToast(totalLength);
                }
                else{
                	handler.postDelayed(r, 16);
                }
			}

			@Override
			public int getOpacity() {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public void setAlpha(int alpha) {
				// TODO Auto-generated method stub
			}
			@Override
			public void setColorFilter(ColorFilter cf) {
				// TODO Auto-generated method stub

			}
        });
        shake = new ShakeClass((SensorManager)getSystemService(SENSOR_SERVICE), null);
    }
}